package com.jy.oms.framework.asyn.task.core;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.system.SystemUtil;
import com.jy.oms.framework.asyn.task.util.ServerConfigAdapter;
import org.apache.commons.collections4.CollectionUtils;

/**
 * 任务执行全局参数
 *
 * @author liuquan
 */
public class ExecutorContext {

    private static ExecutorConfig executorConfig;

    public static ExecutorConfig init(ExecutorConfig executorConfig) {
        if (ExecutorContext.executorConfig != null) {
            return ExecutorContext.executorConfig;
        }

        ExecutorContext.executorConfig = new ExecutorConfig();
        //防御性拷贝
        BeanUtil.copyProperties(executorConfig, ExecutorContext.executorConfig);

        return ExecutorContext.executorConfig;
    }

    public static ExecutorConfig getExecutorConfig() {
        return executorConfig;
    }

    public static boolean isDev() {
        return !SystemUtil.getOsInfo().isLinux();
    }

    public static boolean isTest(){
        return ServerConfigAdapter.isTest() || ServerConfigAdapter.isPressure();
    }

    public static boolean isDevOrTest(){
        return isDev() || isTest();
    }

    public static boolean isAbleAlarm() {
        if (executorConfig.getAbleAlarm() != null) {
            return executorConfig.getAbleAlarm();
        }

        return ServerConfigAdapter.isProd() || ServerConfigAdapter.isStg();
    }

    /**
     * 能否运行异步任务
     */
    public static boolean isEnableTaskExecute() {
        if (executorConfig == null) {
            return false;
        }

        return executorConfig.isEnableTaskExecutor();
    }

    public static boolean isBusinessException(Throwable e) {
        if (executorConfig == null || CollectionUtils.isEmpty(executorConfig.getBusinessExceptions())) {
            return false;
        }

        for (Class<? extends Throwable> businessException : executorConfig.getBusinessExceptions()) {
            if (businessException.isInstance(e)) {
                return true;
            }
        }

        return false;
    }
}
